package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Faculty;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能：用户信息增删查改
 * 作者：刘涵茹
 * 日期：2024/2/14 13:51
 */

@CrossOrigin//跨域支持
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource//通过注解去拿@Service注解中注入容器的函数数据
            UserService userService;


    /**
     * 新增用户信息 post
     */
    @HoneyLogs(operation = "用户", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            user.setCreatedtime(DateUtil.today()); //获取当前的时间(格式: yyyy-mm-dd HH:MM:SS) 如果是today则是yyyy-mm-dd
            if (user.getUserid().length() > 10) {//用户名不超过10
                return Result.error("用户名过长");
            }
            userService.save(user);//service中的函数
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("账号或手机号重复");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 修改用户信息 put
     */
    @HoneyLogs(operation = "用户", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        try {
            if (user.getUserid().length() > 10 || user.getPassword().length() > 8) {//用户名不超过10，密码不超过8
                return Result.error("用户名或密码过长");
            }
            userService.updateById(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("账号或手机号重复");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 单个删除用户信息 delete
     */
    @HoneyLogs(operation = "用户", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")//delete需要通过path相关注解使用
    public Result delete(@PathVariable Integer id) {
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && currentUser.getId() != null && id.equals(currentUser.getId())) {
            throw new ServiceException("不能删除当前登录的用户");
        }
        userService.removeById(id);//service中的函数
        return Result.success();
    }

    /**
     * 批量删除用户信息 delete
     */
    @HoneyLogs(operation = "用户", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")//delete需要通过path相关注解使用
    public Result batchDelete(@RequestBody List<Integer> ids) {//得到数组，并传到service中
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null && currentUser.getId() != null && ids.contains(currentUser.getId())) {
            throw new ServiceException("不能删除当前登录的用户");
        }
        userService.removeBatchByIds(ids);//service中的函数
        return Result.success();
    }

    /**
     * 查询全部的用户信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {//得到数组，并传到service中
        List<User> userList = userService.list(new QueryWrapper<User>().orderByDesc("id"));
        //service中的函数
        //select * from user order by id desc
        return Result.success(userList);
    }

    /**
     * 查询所有，返回单个元素列（teacher角色，名字）
     */
    @GetMapping("/selectTeacher")
    public Result selectTeacher() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByDesc("id");  // 默认倒序，让最新的数据在最上面
        queryWrapper.like("role","教师");
        List<User> userList = userService.list(queryWrapper);
        //select * from user order by id desc
        List<String> nameList = userList.stream().map(User::getUsername).collect(Collectors.toList());
        return Result.success(nameList);
    }

    /**
     * 单个条件查询
     * 根据id查询单个的用户信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {//得到数组，并传到service中
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * 分页多个条件模糊查询
     * 根据username,name查询单个的用户信息
     */
    @CrossOrigin
    @GetMapping("/selectByPage")
    public Result selectByPage(
            @RequestParam Integer pageNum,//页数或者页码
            @RequestParam Integer pageSize,//当前页总共有多少条数据 这两个都是前端传参过来的
            @RequestParam String username,
            @RequestParam String userid,
            @RequestParam String role) {//得到数组，并传到service中
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByDesc("id");//默认倒序,让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(userid), "userid", userid);
        queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
        queryWrapper.like(StrUtil.isNotBlank(role), "role", role);
        // select * from user where username like '%#{username}%' and name like '%#{name}%' and role like '%#{role}%'
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);//service中的函数
        return Result.success(page);
    }

    /**
     *导出数据
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String userid,
                           @RequestParam(required = false) String role,
                           @RequestParam(required = false) String ids,
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!StrUtil.isBlank(ids)){
            //stream流 将字符串的list转换成integer的list ["1","2","3","4"] => [1,2,3,4]
            List<Integer> idsArr1 = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
            queryWrapper.in("id",idsArr1);//判断id是否在idsArr1里面,是就导出
        }else {
            // 全部/查询导出
            queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
            queryWrapper.like(StrUtil.isNotBlank(userid), "userid", userid);
            queryWrapper.like(StrUtil.isNotBlank(role), "role", role);
        }
        list = userService.list(queryWrapper); // 查询出当前user表的所有数据
        writer.write(list, true);//获取所有的数据对象

        //设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息表","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream outputStream = response.getOutputStream(); //获取response输出流
        writer.flush(outputStream, true); //将输出流输出到write中,并确定关闭输出流
        writer.close();
        outputStream.flush();//刷新
        outputStream.close();//再关闭一次输出流
    }

}
